package pfc.pfcjoc.entities;

import static playn.core.PlayN.log;

import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.World;

import pfc.pfcjoc.core.pfcjoc;
import pfc.pfcjoc.core.sprites.Sprite;
import pfc.pfcjoc.core.sprites.SpriteLoader;
import playn.core.GroupLayer;
import playn.core.Layer;
import playn.core.ResourceCallback;

public abstract class Element {
  public String name = "Element";
  protected Sprite sprite;
  protected int spriteIndex = 0;
  protected Vec2 position;

  private ResourceCallback<Element> callback;


  // protected float w, h;

  public Element(final World world, final GroupLayer worldLayer, final Vec2 pos) {
    sprite = SpriteLoader.getSprite(getImagePath(), getJsonPath());
    sprite.addCallback(new ResourceCallback<Sprite>() {
      @Override
      public void done(Sprite sprite) {
        spriteIndex = getFirstSprite();
        sprite.setSprite(spriteIndex);
        sprite.layer().setOrigin(sprite.width() / 2f, sprite.height() / 2f);
        sprite.layer().setScale(getWidth() / sprite.layer().width(), getHeight() / sprite.layer().height());
        sprite.layer().setTranslation(pos.x, pos.y);
        // w = pfcjoc.toPhy(sprite.width());
        // h = pfcjoc.toPhy(sprite.height());
        worldLayer.add(sprite.layer());

        doneLoading();
      }


      @Override
      public void error(Throwable err) {
        log().error("Error loading image!", err);

        callback.error(err);
      }
    });
  }


  public void addCallback(ResourceCallback<Element> callback) {
    this.callback = callback;
    if (isReady()) {
      callback.done(null);
    }
  }


  public void doneLoading() {
    if (callback != null) {
      callback.done(this);
    }
  }


  public void paint(float alpha) {
    float x = position.x;
    float y = position.y;
    sprite.layer().setTranslation(pfcjoc.toPix(x), pfcjoc.toPix(y));
  }


  public void update(float delta) {
  }


  public Layer getLayer() {
    return sprite.layer();
  }


  public Vec2 getPosPhy() {
    return position;
  }


  public void setPosPhy(Vec2 pos) {
    position = pos;
  }


  public abstract String getName();


  public Body getBody() {
    return null;
  }


  public Sprite getSprite() {
    return sprite;
  }


  public boolean isReady() {
    if (sprite == null) {
      return false;
    }
    return sprite.isReady();
  }


  public float getDepth() {
    return sprite.layer().depth();
  }


  public void setDepth(float depth) {
    sprite.layer().setDepth(depth);
  }


  public abstract float getWidth();


  public abstract float getHeight();


  protected abstract int getFirstSprite();


  protected abstract String getImagePath();


  protected abstract String getJsonPath();

}
